(function (w) {
  /*
   * 选择项目组件
   * @param fn   {Function} 项目组件渲染完成后触发  function(arr){}  arr[0] 选中的项目id  arr[1] 所有的项目id
   * @param fn1  {Function} 选择组织架构后触发     function(arr){}  arr[0] 选中的项目id  arr[1] 所有的项目id
   * @param fn2  {Function} 选择具体某个项目后触发  function(arr){}  arr[0] 选中的项目id  arr[1] 所有的项目id
  * */

  // getProduct(
  //   function (arr) {
  //     console.log(arr[0] + arr[1])
  //   },
  //   function (arr) {
  //     console.log(arr[0] + arr[1])
  //   },
  //   function (arr) {
  //     console.log(arr[0] + arr[1])
  //   }
  // )

  w.getProduct = function (fn,fn1,fn2) {
  var companys = {
    init: function () {
      this.selectProject()
      this.getCompanyList()
      this.calcRight()
    },
    // 封装bubble弹窗
      /*
      *  @event  事件对象  Object
      *  @positionX  x方向微调 Number
      *  @positionY  y方向微调 Number
      */
    toShow:function (event,positionX,positionY) {
      $(event.target).parents('body').append('<div class="bubble" style="display:none">' + event.target.innerText + '<span class="sanjiao"></span></div>')
        $('.bubble').css({
          'position':'absolute',
          'width':'auto',
          'min-height':'30px',
          'z-index':'999',
          'line-height':"30px",
          'text-align':'center',
          'border-radius':'5px',
          'left': $(event.target).offset().left + $(event.target).width()/2 + positionX,
          'white-space':'nowrap',
          'top': $(event.target).offset().top + positionY,
          'display':'block',
          'background':'#21242b',
          'padding': '0 10px 0 10px',
          'color':'#fff',
          'transform':'translate(-50%)'
        })
        $('.bubble .sanjiao').css({
          'width': '0',
          'height': '0',
          'position':'absolute',
          'left': '50%',
          'top': '100%',
          'transform': 'translate(-50%,-50%)',
          'border-left': '10px solid transparent',
          'border-right': '10px solid transparent',
          'border-top': '10px solid #21242b',
        })
        $('.js-selected-q').mouseleave(function(event) {
          $('.bubble').css({
            'display':'none',
          })
          $('.bubble').remove()
          $('.sanjiao').remove()
        })
    },
    bubble:function (){
      var self = this
      $('.js-selected-q').mouseenter(self.debounce(function(event) {
        if(event.target.innerText.length<=6){
          return
        }
        if(event.target.localName!=='b'){
          self.toShow(event,30,-20)
          return
        }
        self.toShow(event,30,-20)
      }))
    },
    debounce :function(fn){
      let timer = null
      return function(){
        clearTimeout(timer)
        timer = setTimeout(()=>{
          fn.apply(this,arguments)
        },300)
      }
    },
    calcRight: function () {
      function  calc( bodyWidth ) {
        if (bodyWidth > 1650) {
          var bl = $('.fz-content').offset().left;
          var bw = $('.fz-content').outerWidth()
          var bh = window.screen.availHeight - 86;

          setTimeout(function() {
            $('.js-selected-project').css('height', $('.cm-main-content').outerHeight())
          }, 200);

          $('.js-selected-project').css({
            'position': 'fixed',
            'top': 'auto',
            'right': (bodyWidth - 1220) / 2 - 220 + 'px',
            'border-left': '0',
            'transition': '0s',
            'transform': 'translate(0,0)',
            'border-radius': '4px',
            'overflow': 'hidden',
            'box-shadow': '0 0 8px rgba(0,0,0,0.35)'
          })
          $('.css-pack-up').css({
            'opacity': '1',
            'transform': 'translate(0, 0)',
            'top': '0'
          });
          $('.js-selected-project').unbind('mouseenter')
          $('.js-selected-project').unbind('mouseleave')
          // $('.js-selected-project-bg').hide()
          $('.select-project').css('height', ($(window).height()-215));
        } else {
          $('.js-selected-project').css({
            'position':'fixed',
            'right': 0,
            'top': 0,
            'transition': '0s',
            'border-left': '5px solid #44b549',
            'transform': 'translate(210px,0)',
            'z-index': '999',
            'border-radius': '0',
            'overflow': 'inherit',
            'box-shadow': 'none'
          });
          $('.css-pack-up').css({
            'opacity': '1',
            'transform': 'translate(0,-50%)',
            'top': '50%'
          });

          var flags = 1;
          $('.css-pack-up').click(function(event) {
            if (flags == 1) {
              $('.js-selected-project').css({
                'position':'fixed',
                'right': 0,
                'top': 0,
                'transition': '0.5s all linear',
                'transform': 'translate(0,0)'
              })

              setTimeout(function() {
                $('.select-project').css('height', ($(window).height()-150));
              }, 100);
              flags = 2;
              return;
            }

            if (flags == 2) {
              $('.js-selected-project').css({
                'position':'fixed',
                'right': 0,
                'top': 0,
                'border-left': '5px solid #44b549',
                'transform': 'translate(210px,0)'
              })
              flags = 1;
            }
          })

          $('.js-selected-project').mouseenter(function(event) {
            $('.js-selected-project').css({
              'position':'fixed',
              'right': 0,
              'top': 0,
              'transition': '0.5s all linear',
              'transform': 'translate(0,0)'
            })
            setTimeout(function() {
              $('.select-project').css('height', ($(window).height()-150));
            }, 100);
          })

          $('.js-selected-project').mouseleave(function(event) {
            $('.js-selected-project').css({
              'position':'fixed',
              'right': 0,
              'top': 0,
              'border-left': '5px solid #44b549',
              'transform': 'translate(210px,0)'
            })
          })
        }

      }

      calc(document.body.offsetWidth)



      $(w).resize(function(event) {
        var bodyWidth = document.body.offsetWidth;
        calc(bodyWidth)
      });
    },

    //选择项目
    selectProject: function () {
      var _self = this;

      $('.select-project').unbind().on('click','.js-selected-q b',function (e) {
        $(this).parent('div').siblings('ul').toggleClass('hide');
        $(this).parent('div').toggleClass('active');

        if( $(this).parents('ul').attr('class') === 'third-select' ) {
          $(this).parent().siblings('dl').toggleClass('hide');
        }

        

        if(  $('.first-select .second-select').hasClass('hide') ) {
          // $('.first-select .second-select').find('ul').addClass('hide')
          // $('.first-select .second-select').find('.js-selected-q').removeClass('active')
          $('.first-select .second-select').find('dl').addClass('hide')
          $('.first-select .second-select').find('dl dd').removeClass('active')
        }

        // if( $(this).parents('ul').attr('class') === 'second-select' ) {
        //   // $(this).parents('.second-select li').siblings('li').find('.js-selected-q').removeClass('active')
        //   $(this).parents('.second-select li').siblings('li').find('.third-select').addClass('hide')
        //   $(this).parents('.second-select li').siblings('li').find('.third-select dl').addClass('hide')
        // }

      })

      $('.js-selected-project-box').unbind().on('click','dd', function () {
        
          $(this).toggleClass('active')
          $(this).parents().find('.js-q').removeClass('active')
          // 存储所有选中的项目id到本地存储中
          var projectIDsIn = [], projectIDs = [], arrtemp = [];
          $('.select-project dd').each(function(index, el) {
            if ($(el).hasClass('active')) {
              projectIDsIn.push($(el).attr('data-id'))
            }
            projectIDs.push($(el).attr('data-id'))
          })
          arrtemp.push(projectIDsIn, projectIDs)
          fn2 && fn2(arrtemp)
      })

      $('.js-selected-project').unbind().on('click','.js-q', function (e) {

        setTimeout(function() {
          var projectIDsIn = [], projectIDs = [], arrtemp = [];
          $('.select-project dd').each(function(index, el) {
            if ($(el).hasClass('active')) {
              projectIDsIn.push($(el).attr('data-id'))
            }
            projectIDs.push($(el).attr('data-id'))
          })
          arrtemp.push(projectIDsIn, projectIDs)
          fn1 && fn1(arrtemp)
        }, 200);

        if( !$(this).hasClass('active') ) {
          $(this).addClass('active')
        } else {
          $(this).removeClass('active')
        }

        var parent = $(this).parent().parent().parent();  // ul标签
        //  一级目录
        if ( parent.attr('class') === 'first-select' ) {
          if ( $(this).hasClass('active') ) {
            $(this).parent().siblings('ul').find('.js-q').addClass('active')
            $(this).parent().siblings('ul').find('dd').addClass('active')
          } else {
            $(this).parent().siblings('ul').find('.js-q').removeClass('active')
            $(this).parent().siblings('ul').find('dd').removeClass('active')
          }
        }

        // 二级目录
        if ( parent.attr('class') === 'second-select' ) {
          if ( $(this).hasClass('active') ) {
            $(this).parent().siblings('ul').find('.js-q').addClass('active')
            $(this).parent().siblings('ul').find('dd').addClass('active')
          } else {
            $(this).parent().siblings('ul').find('.js-q').removeClass('active')
            $(this).parent().siblings('ul').find('dd').removeClass('active')
            $(this).parents('.second-select').siblings('.js-selected-q').find('.js-q').removeClass('active')
          }
        }

        // 三级目录
        if ( parent.attr('class') === 'third-select' ) {
          if ( $(this).hasClass('active') ) {
            $(this).addClass('active')
            $(this).parent().siblings('dl').find('dd').addClass('active')
          } else {
            $(this).parents('ul').siblings('.js-selected-q').find('.js-q').removeClass('active')
            $(this).parent().siblings('dl').find('dd').removeClass('active')
          }
        }
      })
    },

    //获取集团大区公司
    getCompanyList:function () {
      var _self = this;
      hlhttp.get({
          url:'user/projects',
          success:function (data) {
            if (data.length) {
              _self.drawCompanyList(data)
            }
            _self.bubble()
          }
      })
    
    },
    drawCompanyList:function (data) {
      var json = {
        group: [],
        area: [],
        company: []
      }

      Array.prototype.removeRepeat = function(){
        var res = [this[0]];
        for(var i = 1 ; i< this.length; i++){
            var repeat = false;
            for(var j=0; j<res.length; j++){
                if(this[i].id == res[j].id){
                    repeat = true;
                }
            }
            if(!repeat){
                res.push(this[i]);
            }
        }
        return res;
      };


    //没有大区集团的时候  id为0
    for (var i = 0; i < data.length; i++) {
      //集团-大区-公司
      if ( data[i].groupId !== undefined && data[i].groupId!=='0' ) {
        json.group.push({
          id: data[i].groupId,
          name: data[i].groupName
        })

        if ( data[i].areaId !== undefined ) {
          json.area.push({
            id: data[i].areaId,
            name: data[i].areaName
          })

          if (data[i].companyId !== undefined) {
            json.company.push({
              id: data[i].companyId,
              name: data[i].companyName,
              aid: data[i].areaId
            })
          }
        }
      }
      //大区公司
      if (data[i].groupId!== undefined && data[i].areaId !== undefined ) {
        json.area.push({
          id: data[i].areaId,
          name: data[i].areaName
        })

        if (data[i].companyId !== undefined) {
          json.company.push({
            id: data[i].companyId,
            name: data[i].companyName,
            aid: data[i].areaId
          })
        }
      }
      //公司
      if (data[i].groupId=='0' && !data[i].areaId && data[i].companyId !== undefined ) {
        json.company.push({
          id: data[i].companyId,
          name: data[i].companyName,
        })
      }
    }

    $('.select-project').html('')
    if ( json.group.length == 0 && json.area.length !== 0 ) {
      $('.select-project').html('<ul class="second-select" style="width:210px;"></ul>')
    }
    if ( json.group.length == 0 && json.area.length == 0 && json.company.length !== 0 ) {
      $('.select-project').html('<ul class="third-select" style="width:210px;"></ul>')
      var resultC = json.company.removeRepeat();
      for(var c=0;c<resultC.length;c++){
        $('.third-select').append('<li><div class="js-selected-q clearfix" data-id="' + resultC[c].id + '"><span class="js-q"></span><b class="ellipsis-1" style="width:155px;">' + resultC[c].name + '</b></div><dl class="hide"></dl></li>')
      }
    }

      var result = json.group.removeRepeat(),str1 = '';
      if (json.group.length) {
        for(var j=0;j<result.length;j++){
            str1 = '<li><div class="js-selected-q clearfix" data-id="' + result[j].id + '">'
                + '<span class="js-q"></span>'
                + '<b class="ellipsis-1" style="width:155px;">' + result[j].name + '</b>'
                + '</div><ul class="second-select hide"></ul></li>'
        }
        $('.select-project').append('<ul class="first-select">'+str1+'</ul>')
      }

      var result1 = json.area.removeRepeat(),str2 = '';
      if(result1[0]){
        for(var a=0;a<result1.length;a++){
          str2 += '<li><div class="js-selected-q clearfix" data-id="' + result1[a].id + '">'
              + '<span class="js-q"></span>'
              + '<b class="ellipsis-1" style="width:155px;">' + result1[a].name + '</b>'
              + '</div><ul class="third-select hide"></ul></li>'
        }
        $('.second-select').append(str2)
      }

      var result2 = json.company.removeRepeat();
      for(var b=0;b<result2.length;b++){
        $('.second-select .js-selected-q').each(function (index, el) {
            if ($(el).attr('data-id') == result2[b].aid) {
                $(el).siblings('ul').append('<li><div class="js-selected-q clearfix" data-id="' + result2[b].id + '"><span class="js-q"></span><b>' + result2[b].name + '</b></div><dl class="hide"></dl></li>')
            }
        })
      }

        for (var i = 0; i < data.length; i++) {
            $('.third-select .js-selected-q').each(function (index, el) {
                if ($(el).attr('data-id') == data[i].companyId) {
                    $(el).siblings('dl').append('<dd data-id="' + data[i].projectId + '"><img src="' + data[i].preview + '?w=70&h=48" alt=""><p>' + data[i].projectName + '</p></dd>')
                }
            })

        }

        var dd = $('.third-select dd');

        for (var ddi = 0; ddi < dd.length; ddi++) {
            for (var ddj = ddi + 1; ddj < dd.length; ddj++) {
              if ( dd.eq(ddi).attr('data-id') == dd.eq(ddj).attr('data-id') ) {
                dd.eq(ddj).remove()
              }
            }
        }

        var projectIDsIn = [], projectIDs = [], arrtemp = [];
        $('.select-project dd').each(function(index, el) {
          if ($(el).hasClass('active')) {
            projectIDsIn.push($(el).attr('data-id'))
          }
          projectIDs.push($(el).attr('data-id'))
        })
        arrtemp.push(projectIDsIn, projectIDs)


        fn && fn(arrtemp)
    }
  }

  companys.init()
  }
}(window))
